package com.sgb.zhaocai.view.demand.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.zhaocai.R;
import com.sgb.zhaocai.databinding.ZcMaterialsbuyFragmentBinding;
import com.sgb.zhaocai.entity.MaterialListEntity;
import com.sgb.zhaocai.entity.RequestBean;
import com.sgb.zhaocai.view.demand.adapter.MaterialsBuyAdapter;
import com.sgb.zhaocai.utils.PickUtil;
import com.sgb.zhaocai.viewmodel.MaterialsBuyModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.List;

/**
 * Time:2021/7/1
 * AUTHOR:F_Q
 * Description:材料采购
 */
public class MaterialsBuyFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener {

    private boolean isLoadMore = false;
    private RequestBean requestBean = new RequestBean();
    private ZcMaterialsbuyFragmentBinding mBinding;
    private MaterialsBuyModel mModel;
    private MaterialsBuyAdapter materialsadapter;
    private ThreeLevelAreaWindow mAddressPop;
    private String longitudes = "";//经度
    private String latitudes = "";//纬度
    private String province = "";//省
    private String city = "";//市
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private String sort = "";//综合排序
    private String useTime = "";//使用时间

    public static final String KEY_TYPE = "type";
    private String type = "";

    public static MaterialsBuyFragment newInstance(String type) {
        MaterialsBuyFragment fragment = new MaterialsBuyFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.zc_materialsbuy_fragment, container, false);
        type = (String) getArguments().get(KEY_TYPE);
        if (TextUtils.equals(type, "1")) {
            mBinding.horizontalscrollview.setVisibility(View.VISIBLE);
        } else {
            mBinding.horizontalscrollview.setVisibility(View.GONE);
        }
        mModel = new ViewModelProvider(this).get(MaterialsBuyModel.class);
        requestBean.setSortMethod("1");
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        super.initView();
        if (materialsadapter == null) {
            materialsadapter = new MaterialsBuyAdapter(getActivity(), null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setHasFixedSize(true);
        //解决数据加载完成后, 没有停留在顶部的问题
        mBinding.recyclerView.setFocusable(false);
        mBinding.recyclerView.setAdapter(materialsadapter);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initDataList();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                requestBean.page++;
                //上拉加载更多
                mModel.MaterialsBuylist(MaterialsBuyFragment.this, requestBean);
            }
        });
        //材料我要报价
        materialsadapter.setOnItemStateOperate(new MaterialsBuyAdapter.OnItemStateOperate() {
            @Override
            public void itemOffer(MaterialListEntity entity) {
                PickUtil.startDemandOffer(getActivity(), entity.getId(),entity.getType(),entity.getCompNo(),"2");
            }
        });
        //初始化popview
        initializePopView();
        mModel.materiallist.observe(this, entities -> setMaterialsBuyList(entities));
        mModel.mAddressData.observe(this, mAddressData -> setAddressData(mAddressData));
        mModel.SortTypeList.observe(this, SortTypeList -> setChooseItemData(1, SortTypeList));
        mModel.UseTimeList.observe(this, UseTimeList -> setChooseItemData(2, UseTimeList));
    }

    //弹窗信息
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case 1://排序方式
                mBinding.sort.setData(data, sort);
                break;
            case 2://使用时间
                mBinding.usetime.setData(data, useTime);
                break;
        }
    }

    //省市区
    private void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            String ProvinceCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE, "");
            if (!TextUtils.isEmpty(ProvinceCode)) {
                mAddressPop.setData(data, true, ProvinceCode);
            } else {
                mAddressPop.setData(data, true);
            }
            mBinding.popLine.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(-2, null);
            } else {
                mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
            }
            mAddressPop.showPopwindow0(mBinding.popLine);
        }
    }

    /**
     * 初始化popview
     */
    private void initializePopView() {
        //地区
        initAddressPopup();
        //综合排序
        mBinding.sort.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        //使用时间
        mBinding.usetime.initPopup(mBinding.grayLayout, mBinding.popLine, this);
    }

    private void initAddressPopup() {
        mBinding.district.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null || scrData.size() == 0) {
                    mModel.getAddressModel(MaterialsBuyFragment.this);
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                    mBinding.district.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                province = "";
                city = "";
                requestBean.setProvince(province);
                requestBean.setCity(city);
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    province = entity.getProvinceNo();
                    requestBean.setProvince(province);
                    mBinding.district.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        city = entity.getCityNo();
                        requestBean.setCity(city);
                        mBinding.district.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                initDataList();
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(1, null);
            } else {
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
            }
        });
    }


    //接口返回shuju
    private void setMaterialsBuyList(List<MaterialListEntity> data) {
        RecyclerRefreshing();
        if (isLoadMore) {
            if (data != null && data.size() > 0) {
                materialsadapter.addDatas(data);
            }
            mBinding.recyclerView.setNoMore(mModel.isLastPage);
        } else {
            if (data != null && data.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                materialsadapter.setDatas(data);
                mBinding.recyclerView.scrollToPosition(0);
                mBinding.recyclerView.setNoMore(mModel.isLastPage);
            } else {
                materialsadapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setVisibility(View.GONE);
            }
        }
    }

    private void RecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    @Override
    protected void onLazyLoad() {
        //获取经纬度
        getLatitudeLongitudeData();
        //请求列表数据信息
        initDataList();
    }

    //请求列表数据信息
    private void initDataList() {
        if (requestBean == null) {
            requestBean = new RequestBean();
        }
        requestBean.setLocalLat(latitudes);
        requestBean.setLocalLng(longitudes);
        isLoadMore = false;
        requestBean.page = 1;
        mModel.MaterialsBuylist(MaterialsBuyFragment.this, requestBean);
    }

    private void getLatitudeLongitudeData() {
        mModel.getSortType();
        mModel.getUseTime(this);
        longitudes = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        latitudes = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        if (TextUtils.isEmpty(longitudes)) {
            longitudes = "0";
        }
        if (TextUtils.isEmpty(latitudes)) {
            latitudes = "0";
        }
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "综合排序":
                mModel.getSortType();
                break;
            case "使用时间":
                mModel.getUseTime(this);
                break;
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "综合排序":
                if (!TextUtils.equals(no, sort)) {
                    sort = no;
                    requestBean.setSortMethod(sort);
                }
                break;
            case "使用时间":
                if (!TextUtils.equals(no, useTime)) {
                    useTime = no;
                    requestBean.setPlanUseTime(useTime);
                }
                break;
        }
        initDataList();
    }
}
